package com.xydtech.rule.controller;

import java.util.List;

import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.exception.BusinessException;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.rule.domain.RuleElementsGroupDetail;
import com.xydtech.rule.domain.RuleElementsItems;
import com.xydtech.rule.domain.RuleExecute;
import com.xydtech.rule.service.IRuleElementsGroupDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.xydtech.common.annotation.Log;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.rule.domain.RuleElementsGroup;
import com.xydtech.rule.service.IRuleElementsGroupService;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.utils.poi.ExcelUtil;
import com.xydtech.common.core.page.TableDataInfo;

/**
 * 规则要素组Controller
 *
 * @author xydtech
 * @date 2024-06-06
 */
@Slf4j
@Controller
@RequestMapping("/rule/group")
public class RuleElementsGroupController extends BaseController {
    private String prefix = "rule/group";

    @Autowired
    private IRuleElementsGroupService ruleElementsGroupService;
    @Autowired
    private IRuleElementsGroupDetailService ruleElementsGroupDetailService;

    @RequiresPermissions("rule:group:view")
    @GetMapping()
    public String group() {
        return prefix + "/group";
    }

    /**
     * 查询规则要素组列表
     */
    @RequiresPermissions("rule:group:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RuleElementsGroup ruleElementsGroup) {
        startPage();
        List<RuleElementsGroup> list = ruleElementsGroupService.selectRuleElementsGroupList(ruleElementsGroup);
        return getDataTable(list);
    }

    /**
     * 导出规则要素组列表
     */
    @RequiresPermissions("rule:group:export")
    @Log(title = "规则要素组", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RuleElementsGroup ruleElementsGroup) {
        List<RuleElementsGroup> list = ruleElementsGroupService.selectRuleElementsGroupList(ruleElementsGroup);
        ExcelUtil<RuleElementsGroup> util = new ExcelUtil<RuleElementsGroup>(RuleElementsGroup.class);
        return util.exportExcel(list, "规则要素组数据");
    }

    /**
     * 新增规则要素组
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存规则要素组
     */
    @RequiresPermissions("rule:group:add")
    @Log(title = "规则要素组", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(RuleElementsGroup ruleElementsGroup) {
        ruleElementsGroup.setCreateBy(getLoginName());
        return toAjax(ruleElementsGroupService.insertRuleElementsGroup(ruleElementsGroup));
    }

    /**
     * 修改规则要素组
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        RuleElementsGroup ruleElementsGroup = ruleElementsGroupService.selectRuleElementsGroupById(id);
        mmap.put("ruleElementsGroup", ruleElementsGroup);
        return prefix + "/edit";
    }

    /**
     * 修改保存规则要素组
     */
    @RequiresPermissions("rule:group:edit")
    @Log(title = "规则要素组", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(RuleElementsGroup ruleElementsGroup) {
        return toAjax(ruleElementsGroupService.updateRuleElementsGroup(ruleElementsGroup));
    }

    /**
     * 删除规则要素组
     */
    @RequiresPermissions("rule:group:remove")
    @Log(title = "规则要素组", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ruleElementsGroupService.deleteRuleElementsGroupByIds(ids));
    }


    @GetMapping("/ruleTest/{groupId}")
    public String ruleTest(@PathVariable("groupId") Long groupId, ModelMap mmap) {
        RuleElementsGroupDetail ruleElementsGroupDetail = new RuleElementsGroupDetail();
        ruleElementsGroupDetail.setGroupId(groupId);
        List<RuleElementsGroupDetail> detailList = ruleElementsGroupDetailService.selectRuleElementsGroupDetailList(ruleElementsGroupDetail);
        mmap.put("detailList", detailList);
        RuleElementsGroup ruleElementsGroup = ruleElementsGroupService.selectRuleElementsGroupById(groupId);
        mmap.put("ruleElementsGroup", ruleElementsGroup);
        return prefix + "/ruleTest";
    }

    /**
     * 规则要素组测试
     */
    @PostMapping("/performTheTest")
    @ResponseBody
    public AjaxResult performTheTest(@RequestBody RuleExecute ruleExecute) {
        long round = 0;
        try {
            //获取规则要素数据
            List<RuleElementsItems> ruleElementsList = ruleExecute.getRuleElementsItems();
            // 一个参数是是否开启高精度默认false，第二个参数是是否开启trace。
            ExpressRunner runner = new ExpressRunner(false, false);
            DefaultContext<String, Object> context = new DefaultContext<>();
            for (RuleElementsItems ruleElementsItems : ruleElementsList) {
                //判断要素项类型 1-数字型 2-字符型
                if ("1".equals(ruleElementsItems.getElementsType())) {
                    context.put(ruleElementsItems.getElementsName(), Integer.valueOf(ruleElementsItems.getElementsValue()));
                } else {
                    context.put(ruleElementsItems.getElementsName(), ruleElementsItems.getElementsValue());
                }
            }
            log.info("参数值：" + context);
            String express = ruleExecute.getRuleFormulas().replaceAll("\\r|\\n|\\t", " ");
            log.info("测试公式：" + express);
            Object outcome = runner.execute(express, context, null, false, false);
            round = Math.round(Double.valueOf(outcome.toString()));
            if (round < 0) {
                round = 0;
            }
            log.info("执行规则测试返回结果值：" + round);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("测试失败："+e.getMessage());
        }
        return AjaxResult.success(round);
    }

}
